﻿using System;
using Splendor_Server.script.db;
using Splendor_Server.script.logic.player;
using Splendor_Server.script.logic.room;
using Splendor_Server.script.net;

namespace Splendor_Server.script.logic.msg
{
    public partial class EventHandler
    {
        public static void OnDisconnect(ClientState client)
        {
            Player player = client.player;
            if (player != null)
            {
                string pid = player.GetPlayerId();
                //离开战场
                if (player.IsInRoom())
                {
                    Room room = RoomManager.GetRoom(player.GetRoomId());
                    room.RemovePlayer(pid);
                }

                //保存数据
                DbManager.UpdatePlayerData(pid, client.player.data);
                //移除
                PlayerManager.RemovePlayer(pid);

                Console.WriteLine("[{0}]CloseConnect: Player-{1}", NetManager.GetNowTime(), pid);
            }
        }

        public static void OnTimer()
        {
            CheckPing();
            RoomManager.Update();
        }

        //Ping检查
        private static void CheckPing()
        {
            foreach (ClientState client in NetManager.clients.Values)
            {
                //现在的时间戳
                long timeNow = NetManager.GetTimeStamp();
                if (timeNow - client.lastPingTime <= NetManager.pingInterval * 4) continue;
                Console.WriteLine("[{0}]PingClose: {1}", NetManager.GetNowTime(), client.socket.RemoteEndPoint);
                NetManager.Close(client);
                return;
            }
        }
    }
}